package ldh.maker.freemaker;

import ldh.bean.util.BeanInfoUtil;
import ldh.common.IDEntity;
import ldh.database.Column;
import ldh.maker.util.FreeMakerUtil;

import java.beans.PropertyDescriptor;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PojoMaker extends BeanMaker<PojoMaker> {

	protected Boolean isLombok = false;

	@SuppressWarnings("unchecked")
	public PojoMaker isLombok(boolean isLombok) {
		this.isLombok = isLombok;
		if (isLombok) {
			imports(lombok.Data.class);
		}
		return this;
	}

	public PojoMaker make() {
		data();
		out("bean.ftl", data);
		
		return this;
	}

	public String toString() {
		data();
		return toString("bean.ftl", data);
	}
	
	public void data() {
		check();
		List<Column> columnList = new ArrayList<Column>();
		if (extendsClass != null) {
			List<PropertyDescriptor> pds = BeanInfoUtil.getFields(IDEntity.class);
			List<Column> cls = table.getColumnList();
			for (Column c : cls) {
				boolean add = true;
				for (PropertyDescriptor pd : pds) {
					if (pd.getName().equals(c.getName())) {
						add = false;
						break;
					}
				}
				if (add) columnList.add(c);
			}
			table.setColumnList(columnList);
		} 
		data.put("table", table);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String str=sdf.format(new Date());
		data.put("Author",author);
		data.put("DATE",str);

		for (Column column : table.getColumnList()) {
			if (column.getPropertyClass().isArray()) {
				imports.add(column.getPropertyClass().getComponentType().getName());
			} else {
				imports.add(column.getPropertyClass().getName());
			}
		}
		
		if (table.getMany() != null && table.getMany().size() > 0) {
			this.imports(List.class);
		}

		if (table.getManyToManys() != null && table.getManyToManys().size() > 0) {
			this.imports(List.class);
		}
		
//		if (FreeMakerUtil.isAuth(table)) {
//			this.extend(InstanceAuth.class);
//		}

		data.put("isLombok", isLombok);
		super.data();
	}
	
	public PojoMaker extend(String extend) {
		this.extendsClassName = extend;
		return this;
	}
	
	protected void check() {
		if (table == null) {
			throw new NullPointerException("table must not be null");
		}
		if (className == null || className.trim().equals("")) {
			className = FreeMakerUtil.firstUpper(table.getJavaName());
		}if (fileName == null || fileName.trim().equals("")) {
			fileName = className + ".java";
		}
		super.check();
		if (pack == null && pack.trim().equals("")) {
			throw new NullPointerException("package must not be null");
		}
	}
}
